package com.guet.careapp.controller.rest.controller.hourseKeeping;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.guet.careapp.controller.rest.common.errorCode.Error;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCode;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCodeFactory;
import com.guet.careapp.pojo.rest.AjaxReturn;
import com.guet.careapp.service.IHourseKeepingService;
import com.guet.careapp.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Map;

@Controller
@Path("/service/hourse_keeping")
public class HourseKeepingController {

    @Autowired
    private IHourseKeepingService hourseKeepingService;


    Gson gson = new GsonBuilder().setPrettyPrinting().create();


    /**
     * GET 方法，获取所有的家政服务信息
     *
     * @return json数组
     */
    @GET
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String getInfoList() {
        return gsonObj(Error.Success, hourseKeepingService.getAllInfos());
    }

    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getInfoByKeywords(String json) {
        Map map = ConvertUtils.jsonToMap(json);
        return gsonObj(Error.Success, hourseKeepingService.getByKeyWords(map));
    }

    /**
     * GET 方法，按照id获取家政信息
     *
     * @param id 家政服务的编号id
     * @return
     */
    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String getInfoByInfoID(@PathParam("id") final String id) {
        return gsonObj(Error.Success, hourseKeepingService.getByServiceID(id));

    }

    @POST
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String addInfo(String json) {
        Map map = ConvertUtils.jsonToMap(json);
        return gsonStr(hourseKeepingService.addHourseKeepingInfo(map));
    }

    @DELETE
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteInfo(@PathParam("id") final String id) {
        return gsonStr(hourseKeepingService.deleteHouseInfoByID(id));
    }


    private String gsonStr(Error error) {
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
    }

    private String gsonObj(Error error, Object object) {
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning(), object));
    }

}
